import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { formatMusicTime } from '@/utils/music-time-format'
import { useMapGetters } from '@/hook/use-map'
import { Message } from '@/utils/message'

export function InitDoing() {
  const store = useStore()
  const router = useRouter()
  // 上一首
  const handelPre = () => {
    const row = { playType: 'pre' }
    store.dispatch('music/playMusic', row)
  }
  // 下一首
  const handelNext = () => {
    const row = { playType: 'next' }
    store.dispatch('music/playMusic', row)
  }
  // audio
  const audio = ref<InstanceType<typeof HTMLAudioElement>>()
  //滑块逻辑
  const isPlayMusic = ref(false)
  const musicDuration = ref(0)
  const totalDuration = ref(200)
  const musicDurationChange = () => {
    audio.value!.currentTime = musicDuration.value
  }
  // 监听音乐播放进度 挂载后执行
  onMounted(() => {
    isPlayMusic.value = true
    audio.value?.addEventListener('timeupdate', () => {
      isPlayMusic.value = false
      totalDuration.value = Number(audio.value?.duration)
      musicDuration.value = Number(audio.value?.currentTime)
      store.commit('music/updateDuration', musicDuration.value)
      if (audio.value!.currentTime >= audio.value!.duration) {
        const index = store.state.music.playIndex
        const musicListCount = store.state.music.musicList
        //歌单最后一首歌 没有下一首歌曲了，暂停清除进度
        musicDuration.value = 0
        if (index + 1 >= musicListCount.length) {
          store.commit('music/updateIsPlay', false)
        } else {
          // 自动播放下一首
          const row = { playType: 'next' }
          store.dispatch('music/playMusic', row)
          // 当前为单曲播放状态
          if (musicListCount.length === 0) {
            store.commit('music/updateIsPlay', false)
          }
        }
      }
    })
  })

  const formatTooltip = (val: number) => {
    return formatMusicTime(val * 1000)
  }

  //歌手信息
  const togSingel = () => {
    const url = store.state.music.musicUrl
    if (url !== '') {
      router.push('/main/nowmusic')
    } else {
      Message('当前未播放歌曲！', 'warning')
    }
  }
  //播放按鈕 切换播放暂停
  const handelPause = () => {
    if (audio.value?.currentSrc === '') {
      Message('当前未播放歌曲！', 'warning')
      return
    }
    if (!audio.value?.paused) {
      audio.value?.pause()
    } else {
      audio.value?.play()
    }
    store.commit('music/updateIsPlay')
  }
  //其他按鈕
  const volume = ref(60)
  const volumeChange = () => {
    audio.value!.volume = volume.value / 100
  }
  // 从vuex获取数据 当前音乐详情以及播放地址
  const gettersMusic = useMapGetters('music', [
    'getMusicDetail',
    'getNowMusic',
    'getIsPlay'
  ])

  return {
    handelPre,
    handelNext,
    audio,
    isPlayMusic,
    musicDuration,
    totalDuration,
    musicDurationChange,
    formatTooltip,
    togSingel,
    handelPause,
    volumeChange,
    volume,
    gettersMusic
  }
}
